package com.will.docker.exec.ws;

import com.alibaba.fastjson.JSONObject;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.messages.ExecCreation;
import com.will.docker.exec.util.DockerHelper;
import com.will.docker.exec.util.SSHAgent;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 连接容器执行命令.
 * @author will
 */
@Component
public class HostExecWSHandler extends TextWebSocketHandler {
    private SSHAgent sshAgent;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //获得传参
        String ip=session.getAttributes().get("ip").toString();

        try {
            //在客户端通过webSocket连接时，创建一个SSH的会话
            this.sshAgent = new SSHAgent();
            //这里写上你的远程服务器ip，账号密码。当然你可以抽取成配置文件
            this.sshAgent.initSession(ip, "root", "XYLX1.t!@#");
            //准备执行命令。
            //sshAgent.execCommand(session);
            InputStream inputStream= this.sshAgent.session.getStdout();
  
            OutPutThread outPutThread=new OutPutThread(inputStream,session);
            outPutThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    /**
     * websocket关闭后关闭线程.
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        sshAgent.close();
    }

    /**
     * 获得先输入.
     * @param session
     * @param message 输入信息
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        try {
            //通过工具类的标准输入网远程服务器中写内容
            this.sshAgent.session.getStdin().write(message.getPayload().getBytes());
            this.sshAgent.printWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
